package com.online.web.shiro.biz.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.online.web.shiro.biz.shiro.UserRealm;
import com.online.web.shiro.dao.user.RoleDao;
import com.online.web.shiro.dao.user.UserDao;
import com.online.web.shiro.model.user.RoleInfo;
import com.online.web.shiro.util.lang.JsonUtil;

/**
 * 角色管理
 * 
 * @author tongyufu
 *
 */
@Service
@Transactional
public class RoleBiz {

    @Autowired
    private UserRealm userRealm;
    @Autowired
    private RoleDao   roleDao;
    @Autowired
    private UserDao   userDao;

    /**指定用户的权限树*/
    public List<Map<String, Object>> queryByUser(Integer userId) {
        List<RoleInfo> roles = roleDao.queryAllRole();
        Set<String> userRoles = roleDao.queryByUserId(userId);
        List<Map<String, Object>> tree = new ArrayList<>();

        for (RoleInfo role : roles) {
            Map<String, Object> leaf = new HashMap<>();
            leaf.put("id", role.getId());
            leaf.put("text", role.getRole());
            if (userRoles.contains(role.getRole())) {
                leaf.put("checked", true);
            }
            tree.add(leaf);
        }
        return tree;
    }

    public String save(RoleInfo roleInfo) {
        if (roleInfo.getId() == null) {
            roleDao.saveRole(roleInfo);
        } else {
            roleDao.updateRole(roleInfo);
        }
        //userRealm.clearAllCachedAuthorizationInfo();
        return JsonUtil.toFormJson("操作成功", true);
    }

    public String delete(Integer roleId) {
        userDao.deleteUserRoleByRoleId(roleId);
        roleDao.deleteRolePermission(roleId);
        roleDao.deleteRole(roleId);
        //userRealm.clearAllCachedAuthorizationInfo();
        return JsonUtil.toFormJson("操作成功", true);
    }

    public String authorization(String permissions, Integer roleId) {
        roleDao.deleteRolePermission(roleId);
        for (String permissionId : permissions.split(",")) {
            roleDao.saveRolePermission(roleId, Integer.parseInt(permissionId));
        }
        //userRealm.clearAllCachedAuthorizationInfo();
        return JsonUtil.toFormJson("操作成功", true);
    }
}
